

interface Pools{
    [name:string]:Cb[]
}

export type Cb = <T=any>(P?:T)=>void

export class  GlobalEvent {

    private pools:Pools = {}

    add(name:string,cb:Cb):boolean{
        const {pools} = this
        if(!pools[name]) pools[name] = []
        if(pools[name].includes(cb)) return false;
        pools[name].push(cb)
        return true;
    }

    emit(name:string,event:any):boolean{
        const {pools} = this
        if(!pools[name]) return false;
        Promise.resolve().then(()=>{
            pools[name].forEach(detail=>{
                detail(event)
            })
        })
        return true
    }

    remove(name:string,cb:Cb):boolean{
        const {pools} = this
        const pool = pools[name]
        if(!pool || !pool.includes(cb)) return false;
        const index = pool.indexOf(cb)
        if(index===-1) return false;
        pool.splice(index,1)
        return true;
    }

}

export default GlobalEvent